package kr.re.etri.snsenabler.server;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpSession;

import kr.re.etri.snsenabler.client.service.DaumCafeService;
import kr.re.etri.snsenabler.server.api.DaumApi;
import kr.re.etri.snsenabler.shared.Data;
import kr.re.etri.snsenabler.shared.LoginProperties;
import kr.re.etri.snsenabler.shared.ServiceResponse;
import kr.re.etri.snsenabler.shared.SocialServiceProperties;
import kr.re.etri.snsenabler.shared.SocialServiceProvider;

import org.scribe.builder.api.Api;
import org.scribe.model.Token;
import org.scribe.model.Verifier;

public class DaumCafeServiceImpl extends AbstractSocialServiceServlet implements DaumCafeService {

	private Logger logger = Logger.getLogger(DaumCafeServiceImpl.class.getName());
	private static final String CONSUMER_KEY = "c141a715-dcba-4bb4-a7fd-378830e91470";
	private static final String CONSUMER_SECRET = "2VidsIy_OXVzbudqeKQ_kbYLjE69xGd3jSJLKDKxl_GI5TvE6VlbjA00";
	private static final String VERIFY_CREDENTIALS = "http://api.twitter.com/1/account/verify_credentials.json";

	@Override
	protected Class<? extends Api> getApi() {
		return DaumApi.class;
	}

	@Override
	protected String getConsumerKey() {
		return CONSUMER_KEY;
	}

	@Override
	protected String getConsumerSecret() {
		return CONSUMER_SECRET;
	}

	private Token getRequestToken(SocialServiceProvider provider) {
		HttpSession session = getThreadLocalRequest().getSession();
		Token requestToken = (Token)session.getAttribute(SessionAttributes.REQUEST_TOKEN + "_" + provider.getName());
		if (requestToken == null) {
			requestToken = getService(provider).getRequestToken();
			session.setAttribute(SessionAttributes.REQUEST_TOKEN + "_" + provider.getName(), requestToken);
		}
		return requestToken;
	}

	@Override
	public ServiceResponse fetchAuthorizationUrl(SocialServiceProvider provider) {
		logger.info("=== Daum Cafe's OAuth Workflow ===");
		String authorizationUrl = getService(provider).getAuthorizationUrl(getRequestToken(provider));
		logger.info("Got the Request Token and Authorize here: " + authorizationUrl);

		Data data = new Data();
		data.put(Data.KEY_1, authorizationUrl);
		ServiceResponse response = new ServiceResponse(data);
		return response;
	}

	@Override
	public ServiceResponse sendVerifier(Data loginData, SocialServiceProvider provider, String verifier) {
		logger.info("Verifier: " + verifier);

		logger.info("Trading the Request Token for an Access Token...");
		Token accessToken = getService(provider).getAccessToken(getRequestToken(provider), new Verifier(verifier));
		logger.info("Got the Access Token: " + accessToken);

//		logger.info("Getting account/verify_credentials...");
//		OAuthRequest request = new OAuthRequest(Verb.GET, VERIFY_CREDENTIALS);
//		getService(provider).signRequest(accessToken, request);
//		Response response = request.send();
//		logger.info("What we got: ");
//		logger.info(String.valueOf(response.getCode()));
//		logger.info(response.getBody());
//		JSONObject jsonObject = (JSONObject)JSONValue.parse(response.getBody());
//		String id = jsonObject.get("id_str").toString();
//		logger.info("ID: " + id);

//{"id_str":"137631629","default_profile":true,"show_all_inline_media":false,"id":137631629,"profile_text_color":"333333","profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1912047372\/image_normal.jpg","profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme1\/bg.png","followers_count":0,"profile_sidebar_border_color":"C0DEED","screen_name":"krischwe","listed_count":0,"utc_offset":null,"name":"\ucd5c\uae30\uc12d","profile_background_tile":false,"friends_count":3,"notifications":false,"url":null,"profile_sidebar_fill_color":"DDEEF6","protected":false,"is_translator":false,"follow_request_sent":false,"created_at":"Tue Apr 27 08:40:18 +0000 2010","lang":"en","default_profile_image":false,"profile_background_color":"C0DEED","description":"","favourites_count":0,"location":"","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1912047372\/image_normal.jpg","profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme1\/bg.png","time_zone":null,"statuses_count":1,"following":false,"contributors_enabled":false,"profile_link_color":"0084B4","geo_enabled":false,"status":{"coordinates":null,"retweeted":false,"truncated":false,"contributors":null,"in_reply_to_status_id_str":null,"place":null,"retweet_count":0,"created_at":"Tue Mar 20 04:50:34 +0000 2012","in_reply_to_user_id_str":null,"favorited":false,"id_str":"181965936788643840","geo":null,"in_reply_to_screen_name":null,"source":"\u003Ca href=\"http:\/\/twitter.com\/#!\/download\/iphone\" rel=\"nofollow\"\u003ETwitter for iPhone\u003C\/a\u003E","in_reply_to_user_id":null,"in_reply_to_status_id":null,"id":181965936788643840,"text":"etri \uacfc\uc81c \ub355\ubd84\uc5d0 \ud2b8\uc704\ud130 \uc2dc\uc791"},"verified":false,"profile_use_background_image":true}

		try {
			Data userData = new Data();
			userData.put(SocialServiceProperties.LOGIN_ID, loginData.get(LoginProperties.LOGIN_ID));
			userData.put(SocialServiceProperties.SERVICE_PROVIDER, provider.getName());
			userData.put(SocialServiceProperties.USER_ID, "xxx");
			userData.put(SocialServiceProperties.ACCESS_TOKEN, accessToken.getToken());
			userData.put(SocialServiceProperties.ACCESS_TOKEN_SECRET, accessToken.getSecret());
			getDbService().insertOAuthSocialService(userData);
			return new ServiceResponse(userData);
		} catch (Exception e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
			return new ServiceResponse(e.getMessage());
		}
	}
}
